/// Created by RongCheng on 2022/7/26.

import 'package:flutter/material.dart';
import 'package:flutter_demo/ui/pages/image/browser/notifier/animation_status_share_data_widget.dart';

import 'drag_gesture_animation.dart';

/// 自定义路由动画,实现透明度渐变动画，飞出返回由 Hero 组合 _pushAnimationController 实现
class DragGesturePageRoute<T> extends PageRoute<T>
    with MaterialRouteTransitionMixin {
  Color backgroundColor;
  DragGesturePageRoute(
      {required this.builder,
      RouteSettings? settings,
      this.maintainState = true,
      this.backgroundColor = Colors.black})
      : super(settings: settings, fullscreenDialog: true);

  //需要跳转的页面
  final WidgetBuilder builder;

  @override
  final bool maintainState;

  //飞出动画
  AnimationController? _pushAnimationController;
  //返回动画
  AnimationController? _popAnimationController;

  AnimationStatusShareData animationStatusShareData =
      AnimationStatusShareData(true);

  @override
  Widget buildContent(BuildContext context) {
    return AnimationStatusShareDataWidget(
        shareData: animationStatusShareData,
        child: DragGestureAnimation(
          pushAnimationController: _pushAnimationController!,
          popAnimationController: _popAnimationController!,
          child: builder(context),
        ));
  }

  // 重写动画
  @override
  AnimationController createAnimationController() {
    if (_pushAnimationController == null) {
      //默认从1变化0， value 是当前值，默认lowerBound
      _pushAnimationController = AnimationController(
        vsync: navigator!.overlay!,
        duration: transitionDuration,
        reverseDuration: transitionDuration,
      );
      _popAnimationController = AnimationController(
        vsync: navigator!.overlay!,
        duration: transitionDuration,
        reverseDuration: transitionDuration,
        value: 1,
      );
    }

    return _pushAnimationController!;
  }

  // 背景，添加淡入淡出的动画, 由两个Controller 进行控制
  @override
  Widget buildTransitions(BuildContext context, Animation<double> animation,
      Animation<double> secondaryAnimation, Widget child) {
    animationStatusShareData.isActive = isActive;
    return Stack(
      children: [
        //透明度渐变 FadeTransition
        FadeTransition(
          // 判断该路由是否在导航上，来使用不同的控制器， 为了解决和 Hero 共用 _pushAnimationController 动画导致时间和值的变化
          opacity:
              isActive ? _pushAnimationController! : _popAnimationController!,
          child: Container(
            color: backgroundColor,
          ),
        ),
        child,
      ],
    );
  }

  String? get title => null;
}
